package ru.housewife.service.prices;

import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.form.UserForm;
import ru.housewife.form.WareForm;
import ru.housewife.form.WareUserPriceForm;
import ru.housewife.model.User;
import ru.housewife.model.Ware;
import ru.housewife.model.WareUserPrice;

/**
 * TODO: add description
 *
 * @author atroshanin
 */
public class AddWareUserPrice implements HibernateAction<WareUserPriceForm> {

    private UserForm userForm;

    private WareForm wareForm;

    private double price;

    public AddWareUserPrice(UserForm userForm, WareForm wareForm, double price) {
        this.userForm = userForm;
        this.wareForm = wareForm;
        this.price = price;
    }

    @Override
    public WareUserPriceForm execute(Session session) {
        User user = (User) session.get(User.class, userForm.getId());
        Ware ware = (Ware) session.get(Ware.class, wareForm.getId());

        if (user == null || ware == null) {
            return null;
        }

        WareUserPrice wareUserPrice = new WareUserPrice();
        wareUserPrice.setUser(user);
        wareUserPrice.setWare(ware);
        wareUserPrice.setPrice(price);
        session.save(wareUserPrice);

        return new WareUserPriceForm(wareUserPrice.getId(), wareForm, userForm, price);
    }
}
